#include "NezhaCMemoryWriteFile.h"
#include "NezhaCFileSystem.h"

using namespace Nezha;
using namespace stream;
using namespace std;

CMemoryWriteFile::CMemoryWriteFile(std::size_t initial)
	: mCurrPos(0)
{
	mBuffer.reserve(initial);
}

int CMemoryWriteFile::write(const void* buffer, u32 sizeToWrite)
{
	if(mCurrPos + sizeToWrite > mBuffer.size())
	{
		if(mBuffer.capacity() < mCurrPos + sizeToWrite)
		{
			mBuffer.reserve((mCurrPos + sizeToWrite) * 2);
		}
		mBuffer.resize(mCurrPos + sizeToWrite);
	}

	memcpy(&mBuffer[mCurrPos], buffer, sizeToWrite);
	mCurrPos += sizeToWrite;

	return sizeToWrite;
}


CMemoryWriteFile::~CMemoryWriteFile()
{
	if (mFilePtr)
    {
        NZ_Delete mFilePtr;
        mFilePtr = NULL;
    }
}

void CMemoryWriteFile::flush()
{
}

bool CMemoryWriteFile::seek(long finalPos, bool relativeMovement)
{
	if(relativeMovement)
	{
		mCurrPos = mCurrPos + finalPos;
		mCurrPos = max(mCurrPos, 0L);

		if(std::size_t(mCurrPos) > mBuffer.size())
		{
			if(mBuffer.capacity() < std::size_t(mCurrPos))
			{
				mBuffer.reserve((mCurrPos + 1) * 2);
			}
			mBuffer.resize(mCurrPos + 1);
		}
	}

	return true;
}

long CMemoryWriteFile::getPos() const
{
	return mCurrPos;
}

const char* CMemoryWriteFile::getFileName() const
{
	return "<memory>";
}

const char* CMemoryWriteFile::getFullPath() const
{
	return "<memory>";
}

const u8* CMemoryWriteFile::getBuffer() const
{
	return &mBuffer[0];
}

std::size_t CMemoryWriteFile::getBufferSize() const
{
	return mBuffer.size();
}

void CMemoryWriteFile::destory()
{
	delete this;
}
